#!/bin/bash
############################################################################
#    Copyright (C) 2010-2015 by Nestor Aguirre                             #
#    nfaguirrec@gmail.com                                                  #
#                                                                          #
#    This program is free software; you can redistribute it and#or modify  #
#    it under the terms of the GNU General Public License as published by  #
#    the Free Software Foundation; either version 2 of the License, or     #
#    (at your option) any later version.                                   #
#                                                                          #
#    This program is distributed in the hope that it will be useful,       #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of        #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         #
#    GNU General Public License for more details.                          #
#                                                                          #
#    You should have received a copy of the GNU General Public License     #
#    along with this program; if not, write to the                         #
#    Free Software Foundation, Inc.,                                       #
#    59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             #
############################################################################

DATA_DIR="/var/tmp/$USER/sjobq.data"
COUNTER_FILE="$DATA_DIR/counter"

##
# @brief
##
function main()
{
	if [ -z "`ps -u $USER | grep "sjobq.d$"`" ]
	then
		echo "### Error ### The daemon sjobq.d is not running"
		echo "              run it using \"sjobq.d start\""
		exit 1
	fi

	BID="X"
	if [ -f "$COUNTER_FILE" ]
	then
		previous=`cat $COUNTER_FILE`
		
		if [ $previous -eq "32767" ]
		then
			BID="0"
		else
			BID=$(( $previous + 1 ))
		fi
		
	else
		echo "0" > $COUNTER_FILE
		BID=`cat $COUNTER_FILE`
	fi
	echo $BID > $COUNTER_FILE

	COMMAND=$*

	echo "id      = $BID"
	echo "command = $COMMAND"
	echo "dir     = $PWD"

	echo "$BID" > $DATA_DIR/$BID.bid
	echo "$COMMAND" > $DATA_DIR/$BID.com
	echo "$PWD" > $DATA_DIR/$BID.pwd
}

main $*
